package com.milhouz.quizzdroid.db;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;

public class QuizzDroidProvider extends ContentProvider {

	private QuizzDroidOpenHelper mOpenHelper;

	private SQLiteDatabase mQuizzDroidsDB;

	public static final String PROVIDER_NAME = "com.milhouz.quizzdroid.db.QuizzDroidProvider";
	public static final Uri QUESTIONS_URI = Uri.parse("content://" + PROVIDER_NAME + "/questions");
	public static final Uri RESPONSES_URI = Uri.parse("content://" + PROVIDER_NAME + "/responses");
	public static final Uri CATEGORIES_URI = Uri.parse("content://" + PROVIDER_NAME + "/categories");
	public static final Uri CATEGORY_NAME_URI = Uri.parse("content://" + PROVIDER_NAME + "/categoryname");

	private static final int QUESTIONS = 1;
	private static final int QUESTION_ID = 2;
	private static final int QUESTION_RESPONSES = 3;
	private static final int CATEGORIES = 4;
	private static final int CATEGORY_ID = 5;
	private static final int QUESTIONS_BY_CATEGORY_ID = 6;
	private static final int RESPONSES = 7;
	private static final int CATEGORY_NAME = 8;

	private static final UriMatcher URI_MATCHER;
	static {
		URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
		URI_MATCHER.addURI(PROVIDER_NAME, "questions", QUESTIONS);
		URI_MATCHER.addURI(PROVIDER_NAME, "questions/#", QUESTION_ID);
		URI_MATCHER.addURI(PROVIDER_NAME, "questions/#/responses", QUESTION_RESPONSES);
		URI_MATCHER.addURI(PROVIDER_NAME, "categories", CATEGORIES);
		URI_MATCHER.addURI(PROVIDER_NAME, "categories/#", CATEGORY_ID);
		URI_MATCHER.addURI(PROVIDER_NAME, "questions/category/#", QUESTIONS_BY_CATEGORY_ID);
		URI_MATCHER.addURI(PROVIDER_NAME, "responses", RESPONSES);
		URI_MATCHER.addURI(PROVIDER_NAME, "categoryname/#", CATEGORY_NAME);
	}

	@Override
	public boolean onCreate() {
		mOpenHelper = new QuizzDroidOpenHelper(getContext());
		mQuizzDroidsDB = mOpenHelper.getWritableDatabase();
		return (mQuizzDroidsDB == null) ? false : true;
	}

	@Override
	public String getType(Uri uri) {
		switch (URI_MATCHER.match(uri)) {
		case QUESTIONS:
			return "vnd.android.cursor.dir/vnd.quizzdroid.questions";
		case QUESTION_ID:
			return "vnd.android.cursor.item/vnd.quizzdroid.question";
		case QUESTION_RESPONSES:
			return "vnd.android.cursor.item/vnd.quizzdroid.potentialresponses";
		case CATEGORIES:
			return "vnd.android.cursor.dir/vnd.quizzdroid.categories";
		case CATEGORY_ID:
			return "vnd.android.cursor.item/vnd.quizzdroid.category";
		case CATEGORY_NAME:
			return "vnd.android.cursor.item/vnd.quizzdroid.categoryname";
		case QUESTIONS_BY_CATEGORY_ID:
			return "vnd.android.cursor.dir/vnd.quizzdroid.questionscat";
		case RESPONSES:
			return "vnd.android.cursor.dir/vnd.quizzdroid.responses";
		default:
			throw new IllegalArgumentException("Unsupported URI: " + uri);
		}
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
		// Choose the table to request following the URI
		if (URI_MATCHER.match(uri) == CATEGORY_ID || URI_MATCHER.match(uri) == CATEGORIES || URI_MATCHER.match(uri) == CATEGORY_NAME) {
			sqlBuilder.setTables(QuizzDroidConstants.TABLE_NAME_CATEGORIES);
		} else if (URI_MATCHER.match(uri) == RESPONSES || URI_MATCHER.match(uri) == QUESTION_RESPONSES) {
			sqlBuilder.setTables(QuizzDroidConstants.TABLE_NAME_RESPONSES);
		} else if (URI_MATCHER.match(uri) == -1) { // XXX BUG DU CATEGORY_NAME_URI
			sqlBuilder.setTables(QuizzDroidConstants.TABLE_NAME_CATEGORIES);
		} else {
			sqlBuilder.setTables(QuizzDroidConstants.TABLE_NAME_QUESTIONS);
		}
		// Choose the conditions request following the URI
		if (URI_MATCHER.match(uri) == QUESTION_ID) {
			// Querying a particular question
			sqlBuilder.appendWhere(QuizzDroidConstants.ID + " = " + uri.getPathSegments().get(1));
		} else if (URI_MATCHER.match(uri) == CATEGORY_ID) {
			// Querying a particular category by id
			sqlBuilder.appendWhere(QuizzDroidConstants.ID + " = " + uri.getPathSegments().get(1));
		} else if (URI_MATCHER.match(uri) == CATEGORY_NAME) {
			// Querying a particular category by name
			sqlBuilder.appendWhere(QuizzDroidConstants.COLUMN_NAME_LABEL + " = \"" + uri.getPathSegments().get(1) + "\"");
		} else if (URI_MATCHER.match(uri) == QUESTION_RESPONSES) {
			// Querying a particular category
			sqlBuilder.appendWhere(QuizzDroidConstants.COLUMN_NAME_QUESTION_ID + " = " + uri.getPathSegments().get(1));
		} else if (URI_MATCHER.match(uri) == QUESTIONS_BY_CATEGORY_ID) {
			// Querying all questions of a category
			sqlBuilder.appendWhere(QuizzDroidConstants.COLUMN_NAME_CATEGORY_ID + " = " + uri.getPathSegments().get(2));
		} else if (URI_MATCHER.match(uri) == -1) { // XXX BUG DU CATEGORY_NAME_URI
			sqlBuilder.appendWhere(QuizzDroidConstants.COLUMN_NAME_LABEL + " = \"" + uri.getPathSegments().get(1) + "\"");
		}
		Cursor c = sqlBuilder.query(mQuizzDroidsDB //
				, projection //
				, selection //
				, selectionArgs //
				, null //
				, null //
				, sortOrder);

		c.setNotificationUri(getContext().getContentResolver(), uri);
		return c;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		long rowID = 0;
		Uri uriWithId = null;
		switch (URI_MATCHER.match(uri)) {
		case QUESTIONS:
			rowID = mQuizzDroidsDB.insert(QuizzDroidConstants.TABLE_NAME_QUESTIONS, "", values);
			if (rowID > 0) { // if added successfully
				uriWithId = ContentUris.withAppendedId(QUESTIONS_URI, rowID);
			}
			break;
		case RESPONSES:
			rowID = mQuizzDroidsDB.insert(QuizzDroidConstants.TABLE_NAME_RESPONSES, "", values);
			if (rowID > 0) { // if added successfully
				uriWithId = ContentUris.withAppendedId(RESPONSES_URI, rowID);
			}
			break;
		case CATEGORIES:
			rowID = mQuizzDroidsDB.insert(QuizzDroidConstants.TABLE_NAME_CATEGORIES, "", values);
			if (rowID > 0) { // if added successfully
				uriWithId = ContentUris.withAppendedId(CATEGORIES_URI, rowID);
			}
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
		if (uriWithId != null) {
			getContext().getContentResolver().notifyChange(uriWithId, null);
			return uriWithId;
		}
		throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public int update(Uri uri, ContentValues arg1, String arg2, String[] arg3) {
		throw new SQLException("Update not allowed with the QuizzDroidProvider : " + uri);
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		int count = 0;
		switch (URI_MATCHER.match(uri)) {
		case QUESTIONS:
			count = mQuizzDroidsDB.delete(QuizzDroidConstants.TABLE_NAME_QUESTIONS, selection, selectionArgs);
			break;
		case RESPONSES:
			count = mQuizzDroidsDB.delete(QuizzDroidConstants.TABLE_NAME_RESPONSES, selection, selectionArgs);
			break;
		case CATEGORIES:
			count = mQuizzDroidsDB.delete(QuizzDroidConstants.TABLE_NAME_CATEGORIES, selection, selectionArgs);
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	public int getCategoryMaxId() {
		String query = "SELECT MAX(" + QuizzDroidConstants.ID + ") FROM " + QuizzDroidConstants.TABLE_NAME_CATEGORIES;
		Cursor cursor = mQuizzDroidsDB.rawQuery(query, null);
		int id = 0;
		if (cursor.moveToFirst()) {
			do {
				id = cursor.getInt(0);
			} while (cursor.moveToNext());
		}
		return id;
	}

}
